using ERPBackend.Data;
using Microsoft.EntityFrameworkCore;
using EFCore.NamingConventions;
using ERPBackend.Services;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using System;
using Microsoft.Extensions.DependencyInjection;

namespace ERPBackend
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // 测试DbContext创建已禁用
            // Console.WriteLine("DbContext test completed. Press any key to continue...");
            // Console.ReadKey();
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            // 配置跨域
            builder.Services.AddCors(options =>
            {
                options.AddPolicy(
                    "AllowFrontend",
                    policy =>
                    {
                        policy
                            .WithOrigins("*")
                            .AllowAnyMethod()
                            .AllowAnyHeader();
                    }
                );
            });

            // 配置数据库连接
            builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))
           .UseSnakeCaseNamingConvention()
            );

            builder
                .Services.AddControllers()
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.ReferenceHandler = System
                        .Text
                        .Json
                        .Serialization
                        .ReferenceHandler
                        .Preserve;
                    // 使用PascalCase命名策略，确保JSON属性首字母大写
                    //options.JsonSerializerOptions.PropertyNamingPolicy = null; // null表示使用默认的PascalCase
                });
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            // 配置Autofac作为依赖注入容器
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
    // 自动注册所有以Service结尾的类
    containerBuilder.RegisterAssemblyTypes(typeof(Program).Assembly)
        .Where(t => t.Name.EndsWith("Service"))
        .AsImplementedInterfaces()
        .InstancePerLifetimeScope();

    // 自动注册所有以Controller结尾的类
    containerBuilder.RegisterAssemblyTypes(typeof(Program).Assembly)
        .Where(t => t.Name.EndsWith("Controller"))
        .InstancePerLifetimeScope();
});

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseAuthorization();

            app.UseCors("AllowFrontend");

            app.MapControllers();

            // 播种数据库
            app.SeedDatabase();

            app.Run();
        }
    }

    public static class WebApplicationExtensions
    {
        public static void SeedDatabase(this WebApplication app)
        {
            using (var scope = app.Services.CreateScope())
            {
                var serviceProvider = scope.ServiceProvider;
                try
                {
                    SeedData.Initialize(serviceProvider);
                    Console.WriteLine("Database seeding completed successfully.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("An error occurred while seeding the database: " + ex.Message);
                }
            }
        }
    }
}
